// 石墨工厂表格表单组件
<template>
  <div>
    <div class="com-container">
      <el-row :gutter="40">
        <el-col :md="8">
          <el-input v-model="search" placeholder="请输入关键字">
            <el-button :loading="searchLoading" slot="append" icon="el-icon-search" @click="toSearch" />
          </el-input>
        </el-col>
        <el-col :md="8" :offset="2">
          <!-- 对列表进行扩充 -->
          <slot name="navBar"></slot>
        </el-col>
        <el-col
          :md="4"
          :offset="getNodeRes ? 2 : 12"
          style="padding-right: 10px"
        >
          <el-button
            type="primary"
            icon="el-icon-plus"
            @click="btn('创建')"
            >创 建</el-button
          >
        </el-col>
      </el-row>
    </div>
    <div class="com-container">
      <!-- 动态展示表格列 -->
      <!-- <label>请选择表格需要展示的列：</label> -->
      <!-- table上面的一行复选框 -->
      <el-checkbox-group v-model="checkedTableColumns">
        <!-- 计算属性只筛选出show为true -->
        <el-checkbox
          v-for="column in checkedTableList('idHide')"
          :key="column.prop"
          :label="column.prop"
          >{{ column.name }}</el-checkbox
        > </el-checkbox-group
      ><br />
      <el-table
        v-loading="loadingState"
        ref="filterTable"
        :data="tableData"
        :header-cell-style="getRowClass"
        border
      >
        <!-- 只渲染 show属性是true 的项 -->
        <el-table-column
          :width="item.width"
          v-for="item in bindTableColumns('idBasics')"
          :key="item.id"
          :prop="item.prop"
          :label="item.name"
          align="center"
        >
          <template slot-scope="scope">
            <!-- 如果id = -1 则加上点击事件 -->
            <span
              v-if="item.id == -1"
              style="cursor: pointer; color: rgb(64, 158, 255)"
              @click="btn('查看', scope)"
              >{{ scope.row[scope.column.property] }}</span
            >
            <span v-else>{{ scope.row[scope.column.property] }}</span>
            <!-- <span>{{ scope.row[scope.column.property] }}</span> -->
          </template>
        </el-table-column>
        <!-- 多级表头形式 -->
        <el-table-column
          v-for="item in bindTableColumns('idMultistage')"
          :key="item.id"
          :label="item.name"
        >
          <!-- 渲染多级表头 -->
          <el-table-column
            v-for="itemChildren in item.children"
            :key="itemChildren.id"
            :prop="itemChildren.prop"
            :label="itemChildren.name"
          ></el-table-column>
        </el-table-column>

        <el-table-column label="操作" align="center">
          <template slot-scope="scope">
            <!-- 将三个按钮放入一个盒子里 template只能有一个子盒子 -->
            <div>
              <el-button
                size="mini"
                type="primary"
                @click="btn('编辑', scope)"
                >编辑</el-button
              >
              <el-popover trigger="click" placement="left">
                <!-- click hover -->
                <infoTag :form="scope.row" :kind="kind" />
                <template slot="reference" class="name-wrapper">
                  <el-button type="success" size="mini">查看</el-button>
                  <!-- <el-tag size="medium">查看</el-tag> -->
                </template>
              </el-popover>
              <el-button
                size="mini"
                type="danger"
                @click="deleteData(scope.row)"
                :loading="deleteLoading"
                >删除</el-button
              >
            </div>
          </template>
        </el-table-column>
      </el-table>
      <div
        v-if="tableData.length !== 0"
        style="display: flex; flex-direction: row-reverse; margin-top: 10px"
      >
        <el-pagination
          :current-page="page"
          :page-size="per_page"
          :total="total_count"
          :page-sizes="[10, 20, 50, 100]"
          background
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
  </div>
</template>

<script>
import infoTag from '@/components/infoTag/index.vue'
export default {
  name: '',
  components: {
    infoTag
  },
  // 在子组件里面通过 props接收父组件传过来的数据
  props: ['tableList', 'tableData', 'res', 'operaList', 'total_count', 'kind'],
  data () {
    return {
      deleteLoading: false,
      searchLoading: false,
      getNodeRes: false,
      loadingState: false,
      operaDialog: false,
      dialogTitle: '',
      rules: [],
      operaForm: {}, // operaForm并不需要父子组件传值，只需要传给父组件内容就行了
      per_page: 10, // 分页的页面大小
      // total_count: 0, // 分页的数据总数 总条数
      page: 1, // 分页的当前页
      search: ''
    }
  },
  computed: {
    // 检测表格形式
    bindTableColumns () {
      // 使用闭包
      return function (type) {
        // console.log(type) 只选择该列为show的那个一项  把tablelist先进行过滤
        // console.log('this.tableList', this.tableList)
        let tableList = this.tableList.filter((column) => column.show)
        let permitList = []
        // console.log(tableList)
        // 检测它的类型是否是多级表头
        if (type === 'idBasics') {
          tableList.forEach(column => {
            if (column.id < 100) {
              permitList.push(column)
            }
          })
        } else if (type === 'idMultistage') {
          tableList.forEach(column => {
            // 如果是多级表头的话我给他的id设置成了大于100 所以在这里判断筛选出来
            if (column.id >= 100) {
              permitList.push(column)
            }
          })
        } else {
          console.warn('未传值')
        }
        return permitList
      }
    },
    // 检测筛选框
    checkedTableList () {
      return function (type) {
        let tableList = this.tableList
        let permitList = []
        if (type === 'idHide') {
          tableList.forEach(column => {
            // 如果id > 0 则展示勾选框 <0的默认必须展示 不能选择显隐
            if (column.id >= 0) {
              permitList.push(column)
            }
          })
        }
        return permitList
      }
    },
    /* 这里使用了getter和setter，这样写的好处是不用自己手动监听复选框的选中事件 */
    // 先用get中的过滤器将有show的过滤出来 并按照prop属性将过滤好的按prop分组
    checkedTableColumns: {
      get () {
        // 返回选中的列名  返回选中的prop值
        return this.tableList.filter((column) => column.show).map(column => column.prop)
      },
      set (checked) {
        // 设置表格列的显示与隐藏
        this.tableList.forEach(column => { // 遍历所有的列的prop
          // 如果选中，则设置列显示
          if (checked.includes(column.prop)) { // 如果点击的在刚刚筛选的那个prop列中 就把这列的属性show设置为true 为展示
            // console.log(column)
            column.show = true
          } else {
            // 如果未选中，则设置列隐藏
            column.show = false
            // console.log(column)
          }
        })
      }
    }
  },
  watch: {},
  created () { },
  mounted () {
    // this.getDatas()
    // console.log(this.kind)
    this.getNode()
  },
  methods: {
    // 搜索信息
    toSearch () {
      const params = {
        key: this.search,
        page: this.page,
        per_page: this.per_page
        // search: search,
        // searchName: searchName
      }
      console.log('params', params)
      this.$emit('getData', params)
    },
    // 接口调用
    handleData (handle, index) { // 增和改用同一套页面
      if (handle === '添加') { // 增接口调用
        this.operaForm = {}
        this.opera = 'add'
      } else if (handle === '编辑') { // 改接口调用
        this.operaForm = JSON.parse(JSON.stringify(this.tableData[index]))
        this.updateIndex = index
        this.opera = 'update'
      }
      this.operaDialog = true
      this.dialogTitle = handle
    },
    resCodeOpera (msg) { // 统一处理返回值
      setTimeout(() => {
        // console.log(this.res.data)
        if (this.resCode() === 1000) {
          // this.apiLoading = true
          this.getDatas()
          this.operaDialog = false
          // this.apiLoading = false
          this.$message({
            center: true,
            message: msg + '成功',
            type: 'success'
          })
        } else { // 这里因为错误的返回值往往不变所以不分离
          this.$message.error({
            center: true,
            message: msg + '失败'
          })
        }
      }, 100)
    },
    submitForm () {
      this.$refs.operaForm.validate(async valid => {
        if (valid) {
          if (this.opera === 'add') {
            // 这里获取到res以后保存
            this.$emit('addData', this.operaForm)
            // 设置为异步任务,不然就会在emit之前输出
            this.resCodeOpera('添加')
          } else {
            // 设置为异步任务,不然就会在emit之前输出
            this.$emit('editData', this.operaForm._id, this.operaForm)
            // while (this.res.data === undefined) { sleep }
            this.resCodeOpera('修改')
            this.tableData.splice(Number(this.updateIndex), 1, this.operaForm) // 先删除项目再添加项目
            this.getDatas()
          }
        } else {
          this.$message({
            showClose: true,
            message: '请根据要求将信息填写完整',
            type: 'warning'
          })
        }
      })
    },
    getDatas () { // 查：分页用的查询
      // let searchName = 'name'
      // let search = this.search
      const params = {
        key: this.search,
        page: this.page,
        per_page: this.per_page
        // search: search,
        // searchName: searchName
      }
      console.log('params', params)
      this.$emit('getData', params)
    },
    deleteData (data) { // 删：删除
      console.log('我是子组件 我在给父组件传参', data)
      this.$confirm('此操作将永久删除该表单, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          // this.deleteLoading = true
          this.$emit('deleteData', data) // 发射的事件名、传的参数
          this.resCodeOpera('删除')
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },

    // 基本组件控制
    resCode () {
      return this.res.data.code
    },
    getNode () {
      // 假如上一个节点为slot节点且有内容,则返回true,空出navbar的内容
      // var child = document.getElementsByClassName('el-col el-col-24 el-col-offset-2 el-col-md-4')[0].previousSibling.previousSibling.getAttribute('class')
      // console.log(child)
      let child = document.getElementsByClassName('el-col el-col-24 el-col-offset-2 el-col-md-8')[0]
      // console.log(child.children)
      if (child.children.length === 0) {
        this.getNodeRes = false
      } else {
        this.getNodeRes = true
      }
      // console.log(this.getNodeRes)
      // var parent = child[0].parentNode
      // console.log(parent)
      // var index = Array.prototype.indexOf.call(parent, child)
      // console.log(index)// 1
    },
    getRowClass ({ row, column, rowIndex, columnIndex }) {
      if (rowIndex === 0) {
        return 'background: rgb(240,245,250);color:black '
      } else {
        return ''
      }
    },
    handleSizeChange (value) { // 改变页面大小
      console.log('每页展示' + value + '条')
      this.apiLoading = true
      this.per_page = value
      this.getDatas()
    },
    handleCurrentChange (value) { // 改变页数
      console.log('第' + value + '页')
      this.apiLoading = true
      this.page = value
      this.getDatas()
    },
    checkStr (str) { // 检验字符串长度是否为0
      if (str.length === 0) return true
      else return false
    },
    btn (handle, scope) { // 在封装的组件里写着多个选项 可以供用他们的父组件们使用
      // console.log(scope)
      if (handle === '编辑') {
        this.$router.push({
          name: 'formCheck',
          query: {
            handle,
            info: scope.row,
            kind: this.kind
          }
        })
      } else if (handle === '创建') {
        this.$router.push({
          name: 'formCheck',
          query: {
            handle,
            kind: this.kind
          }
        })
      } else if (handle === '查看') {
        this.$router.push({
          name: 'formCheck',
          query: {
            handle,
            info: scope.row,
            kind: this.kind
          }
        })
      }
    }
  }
}
</script>

<style lang="scss" scoped>
>>> .el-table-column--selection .cell {
  padding-left: 14px;
  padding-right: 0px;
  /* padding-right: 14px; */
}
>>> .el-dialog__header {
  background: #409eff;
  padding: 15px;
  text-align: left;
}
>>> .el-dialog__title {
  color: #e8eeee;
  font-size: 16px;
}
>>> .el-dialog__close {
  color: #e8eeee;
}
.com-container {
  margin-top: 12px !important;
  padding: 12px 0;
  background-color: rgb(255, 255, 255);
}
</style>
